import { View, Text, ScrollView } from '@tarojs/components'
import Taro, {
  useDidShow,
  usePullDownRefresh,
  useShareAppMessage
} from '@tarojs/taro'
import { useCallback, useMemo, useState } from 'react'
import { getWorkspaceList, WorkspaceItem } from '@/services/workspace'
import { fetchProjectList, ProjectItem } from '@/services/project'
import { fetchProjectTypeList, ProjectTypeItem } from '@/services/projectType'
import { openWebview } from '@/utils/webview'

import './index.scss'

const Index = () => {
  const [workspaces, setWorkspaces] = useState<WorkspaceItem[]>([])
  const [workspaceLoading, setWorkspaceLoading] = useState(true)
  const [projects, setProjects] = useState<ProjectItem[]>([])
  const [projectLoading, setProjectLoading] = useState(false)
  const [currentWorkspaceId, setCurrentWorkspaceId] = useState<number | null>(
    null
  )
  const [selectorVisible, setSelectorVisible] = useState(false)
  const [projectTypes, setProjectTypes] = useState<ProjectTypeItem[]>([])
  const [projectTypeLoading, setProjectTypeLoading] = useState(false)
  const [projectTypeError, setProjectTypeError] = useState<string | null>(null)
  const [projectTypesLoaded, setProjectTypesLoaded] = useState(false)
  const [typeSelectorVisible, setTypeSelectorVisible] = useState(false)

  const currentWorkspace = useMemo(
    () => workspaces.find((item) => item.id === currentWorkspaceId) || null,
    [workspaces, currentWorkspaceId]
  )

  const loadProjects = useCallback(async (workspaceId: number) => {
    setProjectLoading(true)
    try {
      const list = await fetchProjectList({ workspaceId })
      setProjects(list)
    } catch (error) {
      setProjects([])
    } finally {
      setProjectLoading(false)
    }
  }, [])

  const loadProjectTypes = useCallback(
    async (options?: { force?: boolean }) => {
      if (projectTypeLoading) {
        return
      }
      if (projectTypesLoaded && !options?.force) {
        return
      }
      setProjectTypeLoading(true)
      setProjectTypeError(null)
      try {
        const list = await fetchProjectTypeList()
        setProjectTypes(list)
        setProjectTypesLoaded(true)
      } catch (error: any) {
        setProjectTypes([])
        setProjectTypeError(error?.message || '项目类型加载失败')
        setProjectTypesLoaded(false)
      } finally {
        setProjectTypeLoading(false)
      }
    },
    [projectTypeLoading, projectTypesLoaded]
  )

  const selectWorkspace = useCallback(
    (workspaceId: number) => {
      setCurrentWorkspaceId(workspaceId)
      Taro.setStorageSync('lastWorkspaceId', workspaceId)
      loadProjects(workspaceId)
      setSelectorVisible(false)
    },
    [loadProjects]
  )

  const loadWorkspaces = useCallback(async () => {
    setWorkspaceLoading(true)
    try {
      const list = await getWorkspaceList()
      setWorkspaces(list)
      if (list.length > 0) {
        const lastId = Number(Taro.getStorageSync('lastWorkspaceId'))
        const targetId = list.some((item) => item.id === lastId)
          ? lastId
          : list[0].id
        setCurrentWorkspaceId(targetId)
        if (targetId) {
          loadProjects(targetId)
        }
      } else {
        setCurrentWorkspaceId(null)
        setProjects([])
      }
    } finally {
      setWorkspaceLoading(false)
      Taro.stopPullDownRefresh()
    }
  }, [loadProjects])

  useDidShow(() => {
    loadWorkspaces()
    loadProjectTypes()
  })

  usePullDownRefresh(() => {
    loadWorkspaces()
    loadProjectTypes({ force: true })
  })

  useShareAppMessage(() => ({
    title: '百积木 · 工作区',
    path: '/pages/index/index'
  }))

  const handleOpenProject = (project: ProjectItem) => {
    openWebview(`/#/project/${project.id}`)
  }

  const ensureWorkspaceSelected = () => {
    if (!currentWorkspaceId) {
      Taro.showToast({ title: '请先选择工作区', icon: 'none' })
      return false
    }
    return true
  }

  const openTypeSelector = () => {
    if (!ensureWorkspaceSelected()) return
    setTypeSelectorVisible(true)
    loadProjectTypes()
  }

  const closeTypeSelector = () => setTypeSelectorVisible(false)

  const navigateToProjectType = (type: ProjectTypeItem) => {
    if (!ensureWorkspaceSelected()) return
    if (!type.dialogPath) {
      Taro.showToast({ title: '该项目类型暂未配置创建页', icon: 'none' })
      return
    }
    const normalizedPath = type.dialogPath.startsWith('/')
      ? type.dialogPath
      : `/${type.dialogPath}`
    const query = [`workspaceId=${currentWorkspaceId}`, `projectTypeId=${type.id}`]
    if (type.code) {
      query.push(`projectTypeCode=${encodeURIComponent(type.code)}`)
    }
    const connector = normalizedPath.includes('?') ? '&' : '?'
    Taro.navigateTo({
      url: `${normalizedPath}${connector}${query.join('&')}`
    })
    closeTypeSelector()
  }

  const renderProjects = () => {
    if (projectLoading) {
      return <View className='home-page__loading'>项目数据加载中...</View>
    }

    if (!projects.length) {
      return (
        <View className='home-page__empty'>
          <Text>当前工作区暂无项目</Text>
          <View className='home-page__type-section'>
            <Text className='home-page__type-title'>请选择项目类型开始创建</Text>
            {projectTypeLoading ? (
              <Text className='home-page__type-hint'>项目类型加载中...</Text>
            ) : projectTypes.length ? (
              <View className='home-page__type-list'>
                {projectTypes.map((type) => (
                  <View
                    key={type.id}
                    className='home-page__type-card'
                    onClick={() => navigateToProjectType(type)}
                  >
                    <Text className='home-page__type-name'>{type.name}</Text>
                    {type.description && (
                      <Text className='home-page__type-desc'>
                        {type.description}
                      </Text>
                    )}
                  </View>
                ))}
              </View>
            ) : (
              <Text className='home-page__type-hint'>
                {projectTypeError || '暂无可用项目类型'}
              </Text>
            )}
          </View>
        </View>
      )
    }

    return projects.map((project) => {
      const updateTime =
        project.updatedAt ||
        (project as any).updateTime ||
        (project as any).modifyTime ||
        ''
      return (
      <View
        key={project.id}
        className='home-page__project-card'
        onClick={() => handleOpenProject(project)}
      >
        <View className='home-page__project-title'>{project.name}</View>
        {project.description && (
          <Text className='home-page__project-desc'>{project.description}</Text>
        )}
        <View className='home-page__project-meta'>
          <Text>
            类型：{project.projectTypeName || `ID ${project.projectTypeId}`}
          </Text>
          {updateTime && <Text>更新时间：{updateTime}</Text>}
        </View>
      </View>
    )})
  }

  return (
    <View className='home-page'>
      <View className='home-page__header'>
        <View
          className='home-page__workspace'
          onClick={() => setSelectorVisible(!selectorVisible)}
        >
          <Text className='home-page__workspace-label'>当前工作区</Text>
          <View className='home-page__workspace-row'>
            <Text className='home-page__workspace-name'>
              {currentWorkspace?.name || '暂无工作区'}
            </Text>
            <Text className='home-page__arrow'>
              {selectorVisible ? '▲' : '▼'}
            </Text>
          </View>
          {currentWorkspace?.description && (
            <Text className='home-page__workspace-desc'>
              {currentWorkspace.description}
            </Text>
          )}
        </View>
        {selectorVisible && (
          <View className='home-page__selector'>
            {workspaceLoading && <Text>加载中...</Text>}
            {!workspaceLoading &&
              workspaces.map((item) => (
                <View
                  key={item.id}
                  className={`home-page__selector-item${
                    item.id === currentWorkspaceId ? ' is-active' : ''
                  }`}
                  onClick={() => selectWorkspace(item.id)}
                >
                  <Text>{item.name}</Text>
                  <Text className='home-page__selector-desc'>
                    {item.description || '暂无描述'}
                  </Text>
                </View>
              ))}
            {!workspaceLoading && !workspaces.length && (
              <View className='home-page__selector-empty'>暂无工作区</View>
            )}
          </View>
        )}

      </View>

      {!workspaces.length && !workspaceLoading && (
        <View className='home-page__blank'>
          <Text>暂无可用工作区，请联系管理员配置</Text>
        </View>
      )}

      <ScrollView scrollY className='home-page__project-list'>
        {renderProjects()}
      </ScrollView>

      <View
        className={`home-page__fab${
          currentWorkspaceId ? '' : ' is-disabled'
        }`}
        onClick={openTypeSelector}
      >
        创建项目
      </View>

      {typeSelectorVisible && (
        <View className='home-page__type-panel' onClick={closeTypeSelector}>
          <View
            className='home-page__type-panel-card'
            onClick={(event) => event.stopPropagation()}
          >
            <Text className='home-page__type-panel-title'>选择项目类型</Text>
            <Text className='home-page__type-panel-subtitle'>不同类型对应不同创建流程</Text>
            <View className='home-page__type-panel-list'>
              {projectTypeLoading ? (
                <Text className='home-page__type-hint'>项目类型加载中...</Text>
              ) : projectTypes.length ? (
                projectTypes.map((type) => (
                  <View
                    key={type.id}
                    className='home-page__type-card'
                    onClick={() => navigateToProjectType(type)}
                  >
                    <Text className='home-page__type-name'>{type.name}</Text>
                    {type.description && (
                      <Text className='home-page__type-desc'>{type.description}</Text>
                    )}
                  </View>
                ))
              ) : (
                <Text className='home-page__type-hint'>
                  {projectTypeError || '暂无可用项目类型'}
                </Text>
              )}
            </View>
            <View className='home-page__type-panel-actions'>
              <View className='home-page__type-panel-button' onClick={closeTypeSelector}>
                取消
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default Index
